package com.lagou.seckill.listen;

import com.lagou.seckill.constant.Constants;
import com.lagou.seckill.constant.StatusEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(consumerGroup = Constants.CONSUMER_GROUP + Constants.DELAY_TOPIC, topic = Constants.DELAY_TOPIC)
public class DelayListener implements RocketMQListener<String> {

    final RedisTemplate redisTemplate;

    public void onMessage(String order) {
        Object orderStatus = redisTemplate.opsForValue().get(order);
        if (!StatusEnum.PAYED.code.equals(orderStatus)) {
            final String commodityId = order.substring(order.lastIndexOf(":") + 1);
            redisTemplate.delete(order);
            log.warn("超时未支付 删除订单:{}", order);
            //恢复库存
            redisTemplate.opsForValue().increment(Constants.STOCK_PREFIX + commodityId);
            log.info("恢复库存:{}", commodityId);
        }
    }
}
